//
//  XZHHomeTableViewCell.m
//  Piece
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "XZHHomeTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "JTSImageInfo.h"
#import "JTSImageViewController.h"
#import "FLWeatherView.h"
#import "FLWeatherInfo.h"
#import <CoreLocation/CoreLocation.h>
#import "Masonry.h"


#define TIMER_INTERVAL_IN_SEC 45.0
#define WEATHER_UPDATE_INTERVAL_IN_MINUTE 30
#define OPEN_WEATHER_MAP_URL @"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=58779be4c7b736be1a7af6666440c628"

#define IOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0)

@class AppDelegate;

@interface XZHHomeTableViewCell () <CLLocationManagerDelegate>
@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger timerFireCount;
@property (strong, nonatomic) CLLocationManager *locationManager;

@property (weak, nonatomic) FLWeatherView *weatherView;
@end

@implementation XZHHomeTableViewCell{
    UILabel *locationLabel;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapImageView:)];
    [self.coverImageView addGestureRecognizer:tapGesture];
    self.coverImageView.userInteractionEnabled = YES;
    
    self.contentsView.layer.cornerRadius = 5;
    self.contentsView.layer.borderColor = [UIColor colorWithRed:0.86 green:0.87 blue:0.88 alpha:0.8].CGColor;
    self.contentsView.layer.cornerRadius = 5;
    self.contentsView.layer.borderWidth = 2;
    
    self.contentLabel.editable = NO;
    self.contentLabel.scrollEnabled = NO;
    
    
#pragma mark 实时监测天气
    _timerFireCount = 0;
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 10.0f;
    if (IOS8) {
        [_locationManager requestAlwaysAuthorization];
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL_IN_SEC target:self selector:@selector(timerUp) userInfo:nil repeats:YES];
    [_timer fire];
    
    FLWeatherView *weatherView = [[FLWeatherView alloc] init];
    weatherView.frame = CGRectMake(self.authorLabel.frame.origin.x, self.authorLabel.frame.origin.y + self
                                   .authorLabel.frame.size.height + 5, 200, 70);
    [self.contentView addSubview:weatherView];
    self.weatherView = weatherView;
    
    locationLabel = [[UILabel alloc] init];
    locationLabel.text = @"北京市";
    locationLabel.font = [UIFont systemFontOfSize:12];
    locationLabel.textColor = [UIColor colorWithRed:0.72 green:0.72 blue:0.72 alpha:1.00];
    [self.contentView addSubview:locationLabel];
    [locationLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weatherView.right).offset(-85);
        make.top.equalTo(weatherView).offset(4);
        make.height.equalTo(70);
        make.width.equalTo(100);
    }];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}


#pragma mark 发送请求获得天气数据
- (void)updateCityWeatherInfoWithCoordinate:(CLLocationCoordinate2D) coordinate {
    NSString *path = [NSString stringWithFormat:OPEN_WEATHER_MAP_URL, coordinate.latitude, coordinate.longitude];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {
            
        }else {
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *icon = resultDict[@"weather"][0][@"icon"];
            NSString *temp = [NSString stringWithFormat:@"%@", resultDict[@"main"][@"temp"]];
            
            FLWeatherInfo *info = [FLWeatherInfo infoWithIcon:icon temperature:temp];
            //            FLWeatherInfo *info = [FLWeatherInfo infoWithIcon:@"00" temperature:@"12"];
            
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.weatherView.info = info;
            }];
        }
    }];
}


- (void)timerUp {
//    [_weatherView setTimeWithDate:[NSDate date]];
//    
//    _timerFireCount++;
//    if (_timerFireCount * TIMER_INTERVAL_IN_SEC > WEATHER_UPDATE_INTERVAL_IN_MINUTE * 60) {
//        _timerFireCount = 0;
        [self updateWeather];
//    }
}

- (void)updateWeather {
    [_locationManager startUpdatingLocation];
}

#pragma mark 定位
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        
    }else {
        [self updateWeather];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *curLocation = [locations lastObject];
    [self updateCityWeatherInfoWithCoordinate:curLocation.coordinate];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:curLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            
            locationLabel.text = city;
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }else if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

-(void)setModel:(XZHHomeModel *)model
{
    if (_model != model) {
        _model = model;
        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init] ;
        [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *inputDate = [inputFormatter dateFromString:model.hp_makettime];
        NSDateFormatter * outputFormatter = [[NSDateFormatter alloc]init];
        [outputFormatter setDateFormat:@"dd MMM,yyyy.EEE"];
        NSString *str = [outputFormatter stringFromDate:inputDate];
        self.timeLabel.text = str;
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 10;// 字体的行间距
        NSDictionary *attributes = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:14],
                                     NSParagraphStyleAttributeName:paragraphStyle
                                     };
        self.contentLabel.attributedText = [[NSAttributedString alloc] initWithString:model.hp_content attributes:attributes];
        //        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName,nil];
        CGRect newRect = [model.hp_content boundingRectWithSize:CGSizeMake(ScreenWidth - 36, 8000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        [self.contentLabel sizeToFit];
        
        self.contentLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, self.timeLabel.frame.size.height + self.timeLabel.frame.origin.y, self.timeLabel.frame.size.width, newRect.size.height + 80);
        
        [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.hp_img_url]placeholderImage:[UIImage imageNamed:@"home_cover_placeholder"]];
        
        self.authorLabel.text = model.hp_author;
        self.titlesLabel.text = model.hp_title;
        
    }
    
}



- (void)didTapImageView:(UITapGestureRecognizer *)sender {
//    self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.view.backgroundColor = [UIColor colorWithRed:0.23 green:0.22 blue:0.22 alpha:0.3];
//    
//     UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapView:)];
//    [self.view addGestureRecognizer:tapGesture];
//    [self.window addSubview:_view];
//    
//    
//    self.tapCoverImageView = [[UIImageView alloc] init];
//    self.tapCoverImageView.frame = CGRectMake(18, 100, ScreenWidth - 36, 280);
//    self.tapCoverImageView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:_tapCoverImageView];
//    [self.tapCoverImageView sd_setImageWithURL:[NSURL URLWithString:self.model.hp_img_url]];
//     [UIView animateWithDuration:0.5 animations:^{
//         
//         self.tapCoverImageView.frame = CGRectMake(0, 200, ScreenWidth, 280);
//         
//     } completion:^(BOOL finished) {
//         
//     }];
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    imageInfo.image = self.coverImageView.image;
    imageInfo.referenceRect = self.coverImageView.frame;
    imageInfo.referenceView = self.coverImageView.superview;
    imageInfo.referenceContentMode = self.coverImageView.contentMode;
    imageInfo.referenceCornerRadius = self.coverImageView.layer.cornerRadius;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    // Present the view controller.
    [imageViewer showFromViewController:(UIViewController *)self.homeVC transition:JTSImageViewControllerTransition_FromOriginalPosition];
}

//- (void)didTapView:(UITapGestureRecognizer *)sender {
//    self.view.hidden = YES;
//}


@end
